# -*- mode: snippet -*-
# name: webpack.conf.js
# key: main
# --
// So you need prepare follow files:
//   - frontend/index.js (@see react-indexjs.yasnippet)
//   - frontend/index.template.ejs (used by HtmlWebpackPlugin, @see html5-webpack.yasnippet)
//   - frontend/components/Home/Home.js
//   - frontend/components/Dashboard/Dashboard.js
//   - frontend/styles/ (storing global css files)
//   - package.json (@see package-reactjs.yasnippet)
//   - webpack.config.js
//   - .babelrc (file contents: {"presets": ["react", ["es2015", {"loose":true}]], "plugins": ["lodash", "transform-object-rest-spread", "transform-runtime"]})

var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var webpack = require('webpack');
var path = require('path');

if(!process.env.NODE_ENV) {
  // make webpack-dev-server happy to run the `webpack`
  process.env.NODE_ENV = 'development';
}

function getSrcDir(child) {
  return process.env.NODE_ENV === 'development'? child: '' + child;
}

function getDistDir() {
  return process.env.NODE_ENV === 'development'? 'frontend-dist/js': 'src/main/resources/static/js';
}

function getFilesToCopy() {
  var list =[
    {from: 'node_modules/bootstrap/dist/css/*', to: '../css/', flatten:true },
    {from: 'node_modules/bootstrap/dist/fonts/*', to: '../fonts/', flatten:true },
    {from: 'node_modules/font-awesome/css/*', to: '../css/', flatten:true },
    {from: 'node_modules/font-awesome/fonts/*', to: '../fonts', flatten:true}
  ];

  if(process.env.NODE_ENV === 'development') {
    list.push({from:'src/main/resources/static/images/*', to: '../images', flatten:true});
  }
  return list;
}

function getWebpackPlugins() {
  var arr = [
    new LodashModuleReplacementPlugin,
    // it's stupid to copy file one by one, but I haven't figured out another way
    new CopyWebpackPlugin(getFilesToCopy()),
    // full moment.js is too big. @see https://github.com/moment/moment/issues/2416
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.DefinePlugin({
      'process.env': {'NODE_ENV': '"production"'}
    }),
    new webpack.optimize.OccurrenceOrderPlugin,
    new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js"),
    new HtmlWebpackPlugin({
      filename: '../index.html',
      template: path.resolve(__dirname, 'frontend/index.template.ejs'),
      inject: 'body',
      cssDir: getSrcDir('/css')
    })
    // new webpack.optimize.DedupePlugin() // @see https://github.com/webpack/webpack/issues/1982
  ];
  if(process.env.NODE_ENV === 'production') {
    arr.push(
      new webpack.optimize.UglifyJsPlugin({
        // Don't beautify output (enable for neater output)
        beautify: false,
        // Eliminate comments
        comments: false,
        screw_ie8: true,
        // Compression specific options
        compress: {
          warnings: false,
          // Drop console statements
          drop_console: true
        },
        // Mangling specific options
        mangle: {
          // Don't mangle function names
          // keep_fnames: true // about 8% js file size increase
        }
      })
    );
  }
  return arr;
}

module.exports = {
  // we don't need source map in dev version because code is NOT uglified
  devtool: process.env.NODE_ENV === 'production'? 'cheap-module-source-map': null,
  entry: {
    app:'./frontend/index.js',
    vendor: [
      'core-js',
      'react',
      'react-dom',
      'react-bootstrap',
      'redux',
      'redux-thunk',
      'react-redux'
    ]
  },
  output: {
    path: path.resolve(__dirname, getDistDir()),
    filename: 'bundle.js',
    publicPath: getSrcDir('/js/')
  },
  // dev web sever setup which has nothing to do with production code
  devServer: {
    historyApiFallback: true,
    compress: true // less page loading time
  },
  plugins: getWebpackPlugins(),
  resolve: {
    extensions: ['', '.js', '.jsx'],
    modules: [
      'frontend',
      'node_modules'
    ],
    // root for es2015 import
    // @see http://moduscreate.com/es6-es2015-import-no-relative-path-webpack/
    root: [
      path.resolve('./frontend/components')
    ]
  },

  module: {
    loaders: [
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "url-loader?limit=10000&minetype=application/font-woff"
      }, {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "file-loader"
      }, {
        test: /\.css$/,
        exclude: /node_modules|styles/, //exclude css in `node_modules` and `styles/`
        loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader'
      }, {
        test: /\.css$/,
        include: /styles/, // global css
        loader: 'style-loader!css-loader!postcss-loader'
      }, {
        test: /\.css$/,
        include: /node_modules/,
        loaders: ['style-loader', 'css-loader']
      }, {
        test: /\.jsx*$/,
        exclude: [/node_modules/, /.+\.config.js/],
        loader: 'babel'
      }, {
        test: /\.(jpe?g|gif|png|svg)$/i,
        loader: 'url-loader?limit=10000'
      }, {
        test: /\.json$/,
        loader: 'json-loader'
      }, {
        test: /\.font.(js|json)$/,
        loader: "style!css!fontgen?embed&types=woff,eot,ttf"
      }
    ]
  },
  postcss: (webpack) => [
    require('postcss-import')({
      // where to search styles
      path: ['frontend/styles'],
      addDependencyTo: webpack
    }),
    require('postcss-simple-vars')({ silent: false}),
    // though IE9+ already supports calc() out of box
    require('postcss-calc')({warnWhenCannotResolve: true}),
    require('postcss-nested')(),
    require('autoprefixer')({ browsers: ['last 2 versions'] })
  ]
};

// Local Variables:
// coding: utf-8
// tab-width: 2
// js-indent-level: 2
// End:
